package com.TeacherInfoServer.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class IdCardNumberUtil {
    public static String getBirthday(String idCardNumber) {
        // 身份证号码长度为15位或18位
        if (idCardNumber.length() != 15 && idCardNumber.length() != 18) {
            throw new IllegalArgumentException("Invalid ID card number");
        }

        String birthdayStr;
        if (idCardNumber.length() == 18) {
            birthdayStr = idCardNumber.substring(6, 14); // 截取出生日期字符串
        } else {
            birthdayStr = "19" + idCardNumber.substring(6, 12); // 截取出生日期字符串，补全年份为4位
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date birthday = sdf.parse(birthdayStr);
            sdf.applyPattern("yyyy-MM-dd");
            return sdf.format(birthday); // 返回格式化后的生日字符串
        } catch (ParseException e) {
            throw new RuntimeException("Failed to parse birthday from ID card number", e);
        }
    }

    public static int getAge(String idCardNumber) {
        String birthdayStr = getBirthday(idCardNumber);
        int age;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = sdf.parse(birthdayStr);
            Calendar cal = Calendar.getInstance();
            int currentYear = cal.get(Calendar.YEAR);
            cal.setTime(birthday);
            int birthYear = cal.get(Calendar.YEAR);
            age = currentYear - birthYear;
            // 如果当前月份小于出生月份，年龄减一
            int currentMonth = cal.get(Calendar.MONTH) + 1;
            int birthMonth = Integer.parseInt(birthdayStr.substring(5, 7));
            if (currentMonth < birthMonth) {
                age--;
            } else if (currentMonth == birthMonth) { // 如果月份相等，判断日期
                int currentDay = cal.get(Calendar.DAY_OF_MONTH);
                int birthDay = Integer.parseInt(birthdayStr.substring(8));
                if (currentDay < birthDay) {
                    age--;
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException("Failed to parse birthday from ID card number", e);
        }
        return age;
    }
}
